package com.iretailer.report.quartz.sendReqularly.util;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.annotation.JSONField;
import com.iretailer.report.quartz.sendReqularly.model.FlowArray;
import com.iretailer.report.util.BeanUtils;
import com.iretailer.report.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Auther: xjw
 * @Date: 2019/8/1 0001 15:28
 * @Description:
 */
@Slf4j
public class CommonUtil {
    public static <T> String Json2CSV(List<T> list, Class<T> target) throws IllegalAccessException {
        List<String> resut = new ArrayList<>(CollectionUtil.isNotEmpty(list) ? list.size() + 1 : 1);
        Field[] fields = BeanUtils.getFields(FlowArray.class);
        List<String> names = new ArrayList<>();
        for (Field f : fields) {
            f.setAccessible(true);
            JSONField field = f.getAnnotation(JSONField.class);
            String fieldName = f.getName();
            if (field != null && StringUtil.notEmpty(field.name())) {
                fieldName = field.name();
            }
            names.add(fieldName);
        }
        resut.add(rowString(names));
        if (CollectionUtil.isNotEmpty(list)) {
            for (T t : list) {
                List<Object> value = new ArrayList<>();
                for (Field f : fields) {
                    value.add(f.get(t));
                }
                resut.add(rowString(value));
            }
        }
        return CollectionUtil.join(resut, StrUtil.LF);
    }


    public static String rowString(List names) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < names.size(); i += 1) {
            if (i > 0) {
                sb.append(',');
            }
            String string = Objects.isNull(names.get(i)) ? "" : String.valueOf(names.get(i));
            if (string.length() > 0 && (string.indexOf(',') >= 0 ||
                    string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0)) {
                sb.append('"');
                int length = string.length();
                for (int j = 0; j < length; j += 1) {
                    char c = string.charAt(j);
                    if (c >= ' ' && c != '"') {
                        sb.append(c);
                    }
                }
                sb.append('"');
            } else {
                sb.append(string);
            }
        }
        return sb.toString();
    }

}
